# coding=utf-8
from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session


from info import constants, db
from info.models import News, User, Comment
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blue

@news_blue.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注的用户信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")

    # 根据不同操作做不同逻辑
    if action == "follow":
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")
        target_user.followers.append(g.user)
    else:
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            target_user.followers.remove(g.user)

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")



@news_blue.route('/<int:news_id>')
@user_login_data
def get_news_detail(news_id):

    # # 用户登录
    # user_id = session.get('user_id')
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    # 点击排行
    news_list_model = []
    try:
        news_list_model = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')

    news_dict_li = []
    for news in news_list_model if news_list_model else []:
        news_dict_li.append(news.to_dict())

    # 查询新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        abort(404)

    news.clicks += 1

    # 判断是否收藏该新闻
    is_collected = False

    if g.user:
        if news in g.user.collection_news:
            is_collected = True

    is_followed = False
    # 判断用户是否关注 和  我自己已经登陆
    if news.user and g.user:
        if news.user in g.user.followed:
            is_followed = True

    # 新闻评论
    comment_model_list = []
    try:
        comment_model_list = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')

    comment_dict_li = []
    for comment in comment_model_list:
        comment_dict_li.append(comment.to_dict())

    data = {
        'user': g.user.to_dict() if g.user else None,
        'news_dict_li': news_dict_li,
        'news': news.to_dict(),
        'is_collected': is_collected,
        'comments': comment_dict_li,
        'is_followed': is_followed
    }

    return render_template('news/detail.html', data=data)


@news_blue.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    user = g.user  #对象
    json_data = request.json
    news_id = json_data.get('news_id')   # news.id
    action = json_data.get('action')

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='数据不存在')

    if action == 'collect':
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存到数据库失败')

    return jsonify(errno=RET.OK, errmsg='操作成功')


@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    # 参数news_id comment
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    json_data = request.json
    news_id = json_data.get('news_id')
    comment_content = json_data.get('comment')
    parent_id = json_data.get('parent_id')

    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='查询数据库错误')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='该新闻不存在')

    # 初始化模型  保存数据
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content

    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存到数据库失败')

    return jsonify(errno=RET.OK, errmsg='ok', data=comment.to_dict())


@news_blue.route('/comment_like', methods=['POST'])
@user_login_data
def set_comment_like():
    """评论点赞"""
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    # 获取参数 comment_id  news_id  action
    comment_id = request.json.get('comment_id')
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 校验参数
    if not all([comment_id, news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    # 校验action

    # 查询评论数据  查不到或者为空

    # 如果是点赞





